import Description from '@/components/Description';
import { ActionType, ProColumns, ProTable } from '@/components/Pro';
import {
  emsControllerConfigControllerLicence,
  emsControllerConfigControllerLicencePage,
  emsControllerConfigControllerUpdateLicenceState,
} from '@/services/ess/emsControl';
import { Button, DatePicker, Form, message, Switch } from 'antd';
import { DescriptionsItemType } from 'antd/es/descriptions';
import { Moment } from 'moment';
import React, { useRef, useState } from 'react';
import { useIntl, useLocation } from 'umi';
import Styles from './emsCtronller.less';

const EmsControllerSerial: React.FC = () => {
  const intl = useIntl();

  // 从 URL 中获取参数
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const deviceCode = queryParams.get('deviceCode') || '';
  const platformCode = queryParams.get('devicePlatformCode') || '';
  const id = Number(queryParams.get('id')) || 0;

  // 当前站点信息
  const siteInfo = [
    {
      label: intl.formatMessage({ id: 'emsController.serial.deviceCode' }),
      children: deviceCode || 'N/A',
    },
    {
      label: intl.formatMessage({ id: 'emsController.serial.platformCode' }),
      children: platformCode || 'N/A',
    },
  ];

  // Add state for table data
  const [, setTableData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

  // Add ref for ProTable to allow manual refresh
  const tableActionRef = useRef<ActionType>();

  // Add function to handle state change
  const handleStateChange = async (checked: boolean, record: any) => {
    try {
      const response = await emsControllerConfigControllerUpdateLicenceState({
        licenceNo: record.licenceNo, // 修改这里：使用 licenceNo 而不是 lcId
        state: checked,
      });

      if (response.success) {
        message.success(
          intl.formatMessage({ id: 'emsController.serial.message.statusUpdateSuccess' }),
        );
        // 只在成功时刷新表格
        tableActionRef.current?.reload();
      } else {
        message.error(
          response.message ||
            intl.formatMessage({ id: 'emsController.serial.message.statusUpdateFailed' }),
        );
      }
    } catch (error) {
      console.error('Error updating licence state:', error);
      message.error(intl.formatMessage({ id: 'emsController.serial.message.statusUpdateFailed' }));
    }
  };

  // Update columns definition
  const columns = [
    {
      title: intl.formatMessage({ id: 'emsController.serial.table.number' }),
      dataIndex: 'id',
      valueType: 'index',
    },
    {
      title: intl.formatMessage({ id: 'emsController.serial.table.effectiveTime' }),
      dataIndex: 'effectiveDatetime',
    },
    {
      title: intl.formatMessage({ id: 'emsController.serial.table.expiryTime' }),
      dataIndex: 'expireDatetime',
    },
    {
      title: intl.formatMessage({ id: 'emsController.serial.table.serialNumber' }),
      dataIndex: 'licenceNo',
      ellipsis: true,
    },
    {
      title: intl.formatMessage({ id: 'emsController.serial.table.status' }),
      dataIndex: 'state',
      render: (state: boolean, record: any) => (
        <Switch
          checked={state}
          onChange={(checked) => handleStateChange(checked, record)}
          checkedChildren={intl.formatMessage({ id: 'emsController.serial.status.enabled' })}
          unCheckedChildren={intl.formatMessage({ id: 'emsController.serial.status.disabled' })}
        />
      ),
    },
    {
      title: intl.formatMessage({ id: 'emsController.serial.table.useStatus' }),
      dataIndex: 'usageStatus',
      render: (usageStatus: boolean) => (
        <span>
          {usageStatus === true
            ? intl.formatMessage({ id: 'emsController.serial.table.used' })
            : intl.formatMessage({ id: 'emsController.serial.table.unused' })}
        </span>
      ),
    },
    {
      title: intl.formatMessage({ id: 'emsController.serial.table.generationTime' }),
      dataIndex: 'createdTime',
    },
  ];

  // Add function to fetch table data
  const fetchTableData = async (
    params: {
      pageSize?: number;
      current?: number;
      keyword?: string;
    } & Record<string, any>,
  ) => {
    setLoading(true);
    try {
      const response = await emsControllerConfigControllerLicencePage({
        pageSize: params.pageSize || 10,
        current: params.current || 1,
        lcId: id,
      });
      if (response.success && response.data) {
        const records = response.data.records || [];
        setTableData(records);
        return {
          data: records,
          success: true,
          total: response.data.total || 0,
        };
      }
      return { data: [], success: false };
    } catch (error) {
      console.error('Error fetching table data:', error);
      return { data: [], success: false };
    } finally {
      setLoading(false);
    }
  };

  interface FormValues {
    startDate: Moment;
    endDate: Moment;
  }

  const [form] = Form.useForm<FormValues>();

  const onFinish = async (values: FormValues) => {
    try {
      const params = {
        lcId: id, // Remove toString(), use the number directly
        effectiveDatetime: values.startDate.format('YYYY-MM-DD HH:mm:ss'),
        expireDatetime: values.endDate.format('YYYY-MM-DD HH:mm:ss'),
      };

      if (!params.lcId) {
        message.error(intl.formatMessage({ id: 'emsController.serial.message.missingDeviceId' }));
        return;
      }

      const response = await emsControllerConfigControllerLicence(params);
      if (response.success) {
        message.success(intl.formatMessage({ id: 'emsController.serial.message.generateSuccess' }));
        // Add this line to refresh the table after successful generation
        tableActionRef.current?.reload();
        // Optionally reset the form
        form.resetFields();
      } else {
        message.error(
          response.message ||
            intl.formatMessage({ id: 'emsController.serial.message.generateFailed' }),
        );
      }
    } catch (error) {
      message.error(intl.formatMessage({ id: 'emsController.serial.message.generateFailed' }));
      console.error('Error generating serial:', error);
    }
  };

  return (
    <div className={Styles['ems-controller-communication']}>
      <h2 className={Styles['ems-controller-title']}>
        {intl.formatMessage({ id: 'emsController.serial.title' })}
      </h2>
      <div className={Styles['ems-controller-site-info']}>
        <div style={{ width: '700px' }}>
          <Description items={siteInfo as unknown as DescriptionsItemType[]} column={2} />
        </div>
      </div>
      <div className={Styles['ems-controller-serial-wrap']}>
        <Form form={form} layout="inline" onFinish={onFinish}>
          <Form.Item
            name="startDate"
            label={intl.formatMessage({ id: 'emsController.serial.form.effectiveTime' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'emsController.serial.form.effectiveTimeRequired',
                }),
              },
            ]}
          >
            <DatePicker
              showTime
              placeholder={intl.formatMessage({
                id: 'emsController.serial.form.selectPlaceholder',
              })}
            />
          </Form.Item>
          <Form.Item
            name="endDate"
            label={intl.formatMessage({ id: 'emsController.serial.form.expiryTime' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'emsController.serial.form.expiryTimeRequired' }),
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (
                    !value ||
                    !getFieldValue('startDate') ||
                    value.isAfter(getFieldValue('startDate'))
                  ) {
                    return Promise.resolve();
                  }
                  return Promise.reject(
                    new Error(intl.formatMessage({ id: 'emsController.serial.form.endDateError' })),
                  );
                },
              }),
            ]}
          >
            <DatePicker
              showTime
              placeholder={intl.formatMessage({
                id: 'emsController.serial.form.selectPlaceholder',
              })}
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              {intl.formatMessage({ id: 'emsController.serial.form.generateButton' })}
            </Button>
          </Form.Item>
        </Form>
      </div>
      <ProTable<any>
        actionRef={tableActionRef}
        columns={columns as ProColumns<any>[]}
        request={fetchTableData}
        search={false}
        pagination={{
          showQuickJumper: true,
        }}
        rowKey="lcId"
        dateFormatter="string"
        headerTitle=""
        style={{ marginTop: 20 }}
        loading={loading}
      />
    </div>
  );
};

export default EmsControllerSerial;
